package com.xayq.orap.oauth.token;

import java.util.Set;

import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.apache.oltu.oauth2.common.message.types.GrantType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.xayq.orap.model.AccessToken;
import com.xayq.orap.utils.CommonUtils;

@Component
public class ClientCredentialsTokenHandler extends AbstractOAuthTokenHandler {

    private static final Logger LOG = LoggerFactory.getLogger(ClientCredentialsTokenHandler.class);


    /**
     * /oauth/token?client_id=credentials-client&client_secret=credentials-secret&grant_type=client_credentials&scope=read write
     * <p/>
     * Response access_token
     * If exist AccessToken and it is not expired, return it
     * otherwise, return a new AccessToken
     * <p/>
     * {"access_token":"38187f32-e4fb-4650-8e4a-99903b66f20e","token_type":"bearer","expires_in":7}
     */
    @Override
    public void handleAfterValidation() throws OAuthProblemException, OAuthSystemException {

    	AccessToken accessToken = oAuthService.retrieveClientCredentialsAccessToken(clientDetails(),
                tokenRequest.getScopes());
        OAuthResponse tokenResponse = createTokenResponse(accessToken, false);

        LOG.debug("'client_credentials' response: {}", tokenResponse);
        CommonUtils.writeOAuthJsonResponse(response, tokenResponse);


    }


	@Override
	protected OAuthResponse validatePlus() throws OAuthSystemException {
		// TODO Auto-generated method stub
		//validate scope
        Set<String> scopes = tokenRequest.getScopes();
        if (!scopes.isEmpty() && excludeScopes(scopes, clientDetails)) {
            return invalidScopeResponse();
        }

        return null;
	}

    

}
